package hr.mlab.app.expenses.activities.type;

import hr.mlab.app.expenses.DatabaseOpenHelper;
import hr.mlab.app.expenses.R;
import hr.mlab.app.expenses.widgets.mLabSpinner;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;

public class TypeGroupDetail extends Activity {
    private Byte     option;
    private Integer  groupId;
    private Integer  categoryId;
    private SQLiteDatabase db;
    private mLabSpinner categorySpinner;
    private Cursor categoryCursor;
    private SpinnerAdapter categoryAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.groupcategorydetail);
    	db = (new DatabaseOpenHelper(this)).getReadableDatabase();
    	
    	// get input parameters
    	option  = getIntent().getByteExtra("option", (byte) 0);
    	groupId = getIntent().getIntExtra("groupId", 0);
    	categoryId = getIntent().getIntExtra("categoryId", 0);
    	
    	categorySpinner = (mLabSpinner) findViewById(R.id.spnCategory);
   	
     	initWidgets();
 	}    
    
    /**
     * Closing activity
     */
    @Override    
    public void onDestroy() {
    	super.onDestroy();
    	categoryCursor.close();
    	db.close();
    }
    
    /**
     * Screen initializing
     */
    public void initWidgets() {
        TextView screenTitle = (TextView)findViewById(R.id.screenTitle);
       
		switch(option) {
		case 1:
			categoryId = 1;
	    	categoryCursor = db.rawQuery("SELECT _id, categoryName FROM " + DatabaseOpenHelper.dbCategories + " as c " +
					 " left outer join " +  DatabaseOpenHelper.dbGroupCategories + " as gc" +
					 " on c._id = gc.categoryId and gc.groupId = ? WHERE gc.groupId is null", 
					 new String[]{groupId.toString()});
			screenTitle.setText(this.getString(R.string.category)+"-"+this.getString(R.string.btnNew));
			break;
		case 4:
			categorySpinner.setFocusable(false);
			categorySpinner.setClickable(false);
	    	categoryCursor = db.rawQuery("SELECT _id, categoryName FROM " + DatabaseOpenHelper.dbCategories + " as c " +
					 " join " +  DatabaseOpenHelper.dbGroupCategories + " as gc" +
					 " on c._id = gc.categoryId WHERE gc.groupId = ?", 
					 new String[]{groupId.toString()});
			screenTitle.setText(this.getString(R.string.category)+"-"+this.getString(R.string.btnDelete));
			initData();
			break;
		default:
			screenTitle.setText(this.getString(R.string.category));
			Toast.makeText(this, this.getString(R.string.error_invalidOption), Toast.LENGTH_LONG).show();
			returnToCaller(false, null);
			break;
		}
		
		fillCategorySpinner();
    }
    
    /**
     * Reading data from database
     */
    public void initData() {
		SQLiteDatabase dbloc = (new DatabaseOpenHelper(this)).getReadableDatabase();
		Cursor cursor = dbloc.rawQuery("SELECT _id, groupName FROM " + DatabaseOpenHelper.dbGroups +
		                    		   " WHERE  _id = ?", new String[]{groupId.toString()});

		try {
			if (cursor.getCount() == 1) {
				cursor.moveToFirst();

				TextView groupName = (TextView)findViewById(R.id.groupName);
				groupName.setText(cursor.getString(cursor.getColumnIndex("groupName")), BufferType.NORMAL);
			} else {
				throw new Exception(); 
			}
		} catch(Exception e) {
			Toast.makeText(this, this.getString(R.string.error_noData), Toast.LENGTH_LONG).show();
			returnToCaller(false, null);
		} finally {
			cursor.close();
			dbloc.close();
		}
    }
    
   /**
     * Filling spinner
     * 
     */
    public void fillCategorySpinner() {

    	startManagingCursor(categoryCursor);
	
		categoryAdapter = new SimpleCursorAdapter(
						  this, 
						  android.R.layout.simple_spinner_item, 
						  categoryCursor, 
						  new String[] { "categoryName" },
						  new int[] { android.R.id.text1 });
		
		categorySpinner.setAdapter(categoryAdapter);
		
		categorySpinner.setSelectionById(categoryId);
    }
    
    /**
     * Button save clicked
     * @param view
     */
    public void saveClick(View view) {
        switch(option) {
        case 1:
        	dbInsert();
        	break;
        case 4:
        	dbDelete();
        	break;
        }
        returnToCaller(false, null);
    }
    
    /**
     * Button cancel clicked
     * @param view
     */
    public void cancelClick(View view) {
    	returnToCaller(false, null);
    }
    
    /**
     * Button ok clicked
     * @param view
     */
    public void okClick(View view) {
    	returnToCaller(false, null);
    }
    
    /**
     * Closing this window
     * @param refreshNeeded
     * @param id
     */
    private void returnToCaller(Boolean refreshNeeded, Integer id) {
        Intent intent = new Intent();
        if(refreshNeeded) {
        	intent.putExtra("categoryId", id);
        }
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
    
    /**
     * Insert new category
     */
    private void dbInsert() {
    	Integer id = null;
    	Long categoryId = null;
    	Boolean refreshNeeded = false;
		SQLiteDatabase dbloc = (new DatabaseOpenHelper(this)).getWritableDatabase();

		try {
			categoryId=categorySpinner.getSelectedItemId();
			
			ContentValues values = new ContentValues();
			values.put("groupId", groupId);
			values.put("categoryId", Integer.parseInt(categoryId.toString()));
			
			id = (int) dbloc.insert(DatabaseOpenHelper.dbGroupCategories, null, values);
			
			if(id < 1)
				throw new Exception();
			
			refreshNeeded=true;
		}
		catch(Exception e) {
			id = null;
			Toast.makeText(this, this.getString(R.string.error_insert), Toast.LENGTH_LONG).show();
		} 
		finally {
			dbloc.close();
			returnToCaller(refreshNeeded, Integer.parseInt(categoryId.toString()));
		}
    }
     
    /**
     * Delete category 
     */
    private void dbDelete() {
    	Integer response = null;
    	Long categoryId = null;
		SQLiteDatabase dbloc = (new DatabaseOpenHelper(this)).getWritableDatabase();

		try {
			categoryId=categorySpinner.getSelectedItemId();
			
			response = dbloc.delete(DatabaseOpenHelper.dbGroupCategories, "groupId=? and categoryId = ?", 
					  			 new String[]{groupId.toString().trim(), categoryId.toString().trim()});
		
			response = 0;
		}
		catch(Exception e) {
			response = null;
			Toast.makeText(this, this.getString(R.string.error_delete), Toast.LENGTH_LONG).show();
		} 
		finally {
			dbloc.close();
			returnToCaller(response != null, response);
		}
    }
}


